﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Jint;
using System.Security.Permissions;
using Jint.Native;
using MongoDB.Bson.IO;

namespace jsweb
{
   public class MVCExecutive
   {
      private readonly HttpListenerContext _context;
      private readonly string _mapping;
      private readonly string _function;
      private readonly bool _post;
      private readonly JintEngine _engine;
      private Session _session;
      private Form _form;

      public MVCExecutive(HttpListenerContext context, string mapping, string function, object query, bool post)
      {
         _context = context;
         _mapping = mapping;
         _function = function;
         _post = post;
         _engine = new JintEngine();
         _engine.DisableSecurity();
         _engine.SetFunction("View", new Func<string, object, object>(View));
         _engine.SetFunction("JSON", new Func<JsObject, string>(JSON));
         _engine.SetParameter("db", new db(_engine));

         // Create form object
         if (post)
            _form = new Form(context, _engine);

         // Create session
         _session = new Session(context, _engine);

         if (query != null)
            _engine.Run("var Query = " + query + ";");
      }

      public object Execute()
      {
         var val = _engine.Run(_function);

         // Save session
         _session.Save();

         return val;
      }

      public string JSON(JsObject jsObject)
      {
         var serialized = jsweb.JsonSerializer.Serialize(jsObject);
         return serialized;
      }
      
      public object View(string viewName, object model)
      {
         var viewContext = new JintEngine(Options.Ecmascript5).SetParameter("Model", model);

         var file = File.ReadAllText("Views/" + _mapping + ".html");
         var regex = new Regex("<@>(.*?)</@>", RegexOptions.Singleline);
         Match match = regex.Match(file);
         while (match.Success)
         {
            // Execute js
            viewContext.SetParameter("result", "");
            var jsResult = viewContext.Run(match.Groups[1].Value);

            file = file.Substring(0, match.Index) + jsResult + file.Substring(match.Index + match.Length);
            match = regex.Match(file);
         }
         return file;
      }
   }
}
